// utils/request.js
import {camelCase,snakeCase} from './index'
export const BASE_URL = 'http://127.0.0.1:3900/api';
let isRefreshing = false; // 防止重复刷新token
let pendingRequests = []; // 存储待重试请求

/**
 * 登录获取新token
 */
const loginAndGetToken = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: (loginRes) => {
        if (!loginRes.code) {
          reject(new Error('获取code失败: ' + loginRes.errMsg));
          return;
        }

        wx.request({
          url: `${BASE_URL}/login`,
          method: "POST",
          data: { code: loginRes.code },
          header: { 'Content-Type': 'application/json' },
          success: (res) => {
            console.log('登录成功--->', res);
            if (res.data && res.data.data && res.data.data.token) {
              wx.setStorageSync('token', res.data.data.token);
              wx.setStorageSync('open_id', res.data.data.user.open_id);
              resolve(res.data.data.token);
            } else {
              reject(new Error('获取token失败'));
            }
          },
          fail: (err) => {
            reject(err);
          }
        });
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

/**
 * 处理401未授权错误
 */
const handleUnauthorizedError = (originalRequest) => {
  if (!isRefreshing) {
    isRefreshing = true;
    
    return loginAndGetToken()
      .then(token => {
        // 处理所有等待中的请求
        processPendingRequests(token);
        // 重试原始请求
        originalRequest.header.Authorization = `Bearer ${token}`;
        return retryRequest(originalRequest);
      })
      .catch(err => {
        // 登录失败，清空队列
        pendingRequests = [];
        throw err;
      })
      .finally(() => {
        isRefreshing = false;
      });
  } else {
    // 如果正在刷新token，将请求加入队列
    return new Promise((resolve, reject) => {
      pendingRequests.push((token) => {
        originalRequest.header.Authorization = `Bearer ${token}`;
        retryRequest(originalRequest)
          .then(resolve)
          .catch(reject);
      });
    });
  }
};

/**
 * 处理等待中的请求
 */
const processPendingRequests = (token) => {
  while (pendingRequests.length > 0) {
    const request = pendingRequests.shift();
    request(token);
  }
};

/**
 * 重试请求
 */
const retryRequest = (config) => {
  return new Promise((resolve, reject) => {
    wx.request({
      ...config,
      success: (res) => {
        if (res.statusCode >= 400) {
          reject(res.data);
        } else {
          resolve(res.data);
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

/**
 * 封装的request方法
 */
const request = (options) => {
  // 获取token
  const token = wx.getStorageSync('token');
  
  // 构造请求配置
  const config = {
    url: `${BASE_URL}${options.url}`,
    method: options.method || 'GET',
    data: snakeCase(options.data) || {},
    header: {
      'Content-Type': 'application/json',
      ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
      ...(options.header || {}),
    },
  };

  return new Promise((resolve, reject) => {
    wx.request({
      ...config,
      success: async (res) => {
        try {
          // 处理401未授权
          if (res.statusCode === 401) {
            // 如果是登录接口本身返回401，直接reject
            if (config.url.includes('/login')) {
              reject(new Error('登录失败'));
              return;
            }
            
            const result = await handleUnauthorizedError(config);
            resolve(camelCase(result));
            return;
          }
          
          // 处理其他错误状态码
          if (res.statusCode >= 400) {
            reject(res.data);
            return;
          }
          
          // 成功响应
          resolve(camelCase(res.data));
        } catch (error) {
          reject(error);
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

export default request;